import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-01-17
 * Time: 11:20
 */


//Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution2 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        // 思路沿用基础的模版，添加一个标志符用于逆序，谁逆序队列里的元素逆序
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null)
            return lists;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        Boolean sign = true;

        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                // 让对头元素的val值进入集合，再让该元素的左右孩子入队
                TreeNode curNode = queue.poll();

                if (curNode != null) {
                    list.add(curNode.val);
                }
                if (curNode.left != null) queue.add(curNode.left);
                if (curNode.right != null) queue.add(curNode.right);
            }
            if (sign == true) {
                lists.add(list);
                sign = false;
            } else {
                Collections.reverse(list);
                lists.add(list);
                sign = true;
            }
        }
        return lists;
    }
}

public class Test2 {
}
